﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Hosting;
using SpiderNet8.Main;
using Microsoft.Extensions.Logging.Abstractions;
using NLog;


var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
builder.AddEnvironmentVariables();

var configuration = builder.Build();


// 提前触发 NLog 的配置加载流程
var config = LogManager.Configuration;


// 创建HostBuilder并配置依赖注入和nlog
var host = Host.CreateDefaultBuilder(args)
    .UseNLog() // 让UseNLog()负责NLog的初始化和配置
    .ConfigureServices((hostContext, services) =>
    {
        services.AddHttpClient();
        services.AddScoped<GetContext>();
        services.AddSingleton<IConfiguration>(configuration);
    })   
    .Build();

// 获取服务实例
var context = host.Services.GetRequiredService<GetContext>();
var logger = host.Services.GetRequiredService<ILogger<Program>>();
var configService = host.Services.GetRequiredService<IConfiguration>();

try
{

    string url = configService["TargetUrl"] ?? "https://www.hangzhou.gov.cn/col/col1229444337/index.html";
    logger.LogInformation($"开始获取URL内容: {url}");

    string htmlContent = await context.GetContentByHtmlAsync(url);

    if (!string.IsNullOrEmpty(htmlContent))
    {
        logger.LogInformation($"成功获取内容，长度: {htmlContent.Length}");
        Console.WriteLine(htmlContent.Substring(0, Math.Min(200, htmlContent.Length)));
    }
    else
    {
        logger.LogWarning("获取的内容为空");
    }
}
catch (Exception ex)
{
    logger.LogCritical(ex, "程序执行过程中发生严重错误");
}
finally
{
    host.Dispose();
    // 让UseNLog()处理NLog的关闭
    // NLog.LogManager.Shutdown();
}